from flask import Blueprint, request, render_template, redirect
from common.libs.Helper import ops_renderJSON, ops_renderErrJSON, ops_render
from common.models.meeting_order import MeetingOrder as Order
from common.models.meeting_meetingroom import MeetingRoom as Room
from common.models.document import Document
from application import db
from common.libs.DataHelper import getCurrentTime
from sqlalchemy import and_
from sqlalchemy import or_
from flask import json
import time
from datetime import date, timedelta
import datetime
import requests
from qiniu import Auth
from qiniu import put_data
from qiniu import BucketManager

meeting_page = Blueprint("meeting_page", __name__)


@meeting_page.route("/changemeetingmark", methods=["GET", "POST"])
def changemeetingmark():
    req = request.values
    id = req['id'] if "id" in req else ""
    mark = req['mark'] if "mark" in req else ""
    type = req['type'] if "type" in req else 1

    a = Order.query.filter_by(id=id).first()
    city = a.city
    date = str(a.meetingdate)
    a.mark = mark
    db.session.commit()
    if type == 1:
        return ops_renderJSON(msg="状态变更成功")
    else:
        return redirect('meetingsearch2?city=' + city + '&date=' + date)


@meeting_page.route("/getmeetingorderdetail", methods=["GET", "POST"])
def getmeetingorderdetail():
    req = request.values
    id = req['id'] if "id" in req else ""
    a = Order.query.filter_by(id=id).first()
    # 准备时间比较
    stime = str(a.meetingstime)
    timeArray_stime = time.strptime(stime, '%Y-%m-%d %H:%M:%S')
    timeStamp_stime = int(time.mktime(timeArray_stime))
    ntime = getCurrentTime()
    timeArray_ntime = time.strptime(ntime, '%Y-%m-%d %H:%M:%S')
    timeStamp_ntime = int(time.mktime(timeArray_ntime))
    timeStamp_mtime = timeStamp_stime - 3600
    # 准备返回参数
    name = a.name
    stime = a.meetingstime
    etime = a.meetingetime
    meetingroom = a.meetingroom
    topic = a.creater.city + a.meetingroom
    if timeStamp_ntime >= timeStamp_mtime:
        return json.dumps(
            {"code": 200, "msg": "查询成功", "name": name, "stime": stime, "etime": etime, "meetingroom": meetingroom,
             "topic": topic, "showmark": 1},
            indent=4,
            sort_keys=True,
            default=str,
            ensure_ascii=False)


    else:
        return json.dumps(
            {"code": 200, "msg": "查询成功", "name": name, "stime": stime, "etime": etime, "meetingroom": meetingroom,
             "topic": topic, "showmark": 0},
            indent=4,
            sort_keys=True,
            default=str,
            ensure_ascii=False)


@meeting_page.route("/getmeetingorderlist", methods=["GET", "POST"])
def getmeetingorderlist():
    req = request.values
    uid = req['uid'] if "uid" in req else ""
    time = getCurrentTime()

    a = Order.query.filter(Order.mark != 0, Order.uid == uid, Order.meetingetime >= time).all()

    # a = Order.query.filter_by(uid=uid,mark=1).all()
    rts = []
    for item in a:
        temp = dict(id=item.id, name=str(item.name), url="../meeting/meetingdetail?id=" + str(item.id))
        rts.append(temp)
    # rts = json.dumps(a, cls=AlchemyEncoder,ensure_ascii=False)
    return json.dumps(rts, ensure_ascii=False)  # rts


@meeting_page.route('/getmeetingroom', methods=['GET', 'POST'])
def getmeetingroom():
    req = request.values
    city = req['city'] if "city" in req else ""
    a = Room.query.filter_by(city=city).all()
    rts = []
    for item in a:
        temp = dict(meetingroom=item.name)
        rts.append(temp)
    # rts = json.dumps(a, cls=AlchemyEncoder,ensure_ascii=False)
    return json.dumps(rts, ensure_ascii=False)  # rts


@meeting_page.route("/meetingorder", methods=["GET", "POST"])
def meetingorder():
    req = request.values
    name = req['name'] if "name" in req else ""
    meetingroom = req['meetingroom'] if "meetingroom" in req else ""
    date = req['meetingdate'] if "meetingdate" in req else "0000-00-00"
    stime = req['stime'] if "stime" in req else "00:00:00"
    etime = req['etime'] if "etime" in req else "00:00:00"
    uid = req['uid'] if "uid" in req else ""
    city = req['city'] if "city" in req else ""
    stime = date + " " + stime
    etime = date + " " + etime

    if stime >= etime:
        return ops_renderErrJSON(msg="会议时间不科学")

    if len(name) < 1:
        return ops_renderErrJSON(msg="请输入会议名称")

    if len(meetingroom) < 1 or meetingroom == "请选择":
        return ops_renderErrJSON(msg="请选择会议室")

    if date == "0000-00-00":
        return ops_renderErrJSON(msg="请选择会议日期")

    if stime == "00:00:00":
        return ops_renderErrJSON(msg="请选择会议开始日期")

    if etime == "00:00:00":
        return ops_renderErrJSON(msg="请选择会议结束日期")
    #
    if len(uid) < 1:
        return ops_renderErrJSON(msg="非法用户，操作失败")

    a = Order.query.filter(
        and_(Order.mark != 0, Order.meetingroom == meetingroom, Order.meetingstime <= stime,
             Order.meetingetime >= stime),
        or_(Order.mark != 0, Order.meetingroom == meetingroom, Order.meetingstime <= etime,
            Order.meetingetime >= etime),
        or_(Order.mark != 0, Order.meetingroom == meetingroom, Order.meetingstime >= stime,
            Order.meetingetime <= etime)).first()

    if a is None:
        order = Order()
        order.name = name
        order.meetingdate = date
        order.meetingstime = stime
        order.meetingetime = etime
        order.meetingroom = meetingroom
        order.mark = 1
        order.uid = uid
        order.city = city
        order.created_time = order.updated_time = getCurrentTime()
        db.session.add(order)
        db.session.commit()
        return ops_renderJSON(msg="会议室预约成功", code=200)
    else:
        return ops_renderJSON(msg="会议时间冲突", code=405)


@meeting_page.route("/lookupmeeting", methods=["GET", "POST"])
def lookupmeeting():
    req = request.values
    meetingroom = req['meetingroom'] if "meetingroom" in req else ""
    date = req['date'] if "date" in req else "1000-01-01"

    # a = Order.query.filter_by(meetingroom=meetingroom, meetingdate=date, mark=1).all()
    a = Order.query.filter(Order.meetingroom==meetingroom, Order.meetingdate==date, Order.mark!= 0).all()
    rts = []
    for item in a:
        temp = dict(name=item.name, stime=str(item.meetingstime), etime=str(item.meetingetime),
                    creatername=item.creater.nickname, createrdep=item.creater.department)
        rts.append(temp)
    # rts = json.dumps(a, cls=AlchemyEncoder,ensure_ascii=False)
    return json.dumps(rts, ensure_ascii=False)  # rts


# 管理员获得申请列表
@meeting_page.route("/showmeetingorder", methods=["GET", "POST"])
def showmeetingorder():
    req = request.values
    city = req['city'] if "city" in req else ""
    stime = req['stime'] if "stime" in req else ""
    etime = req['etime'] if "etime" in req else ""
    mark = req['mark'] if "mark" in req else ""

    if len(stime) < 1:
        return ops_renderErrJSON(msg="请输入开始时间")
    if len(etime) < 1:
        return ops_renderErrJSON(msg="请输入结束时间")
    else:
        a = Order.query.filter(Order.mark == mark, Order.city == city, Order.meetingstime <= etime,
                               Order.meetingstime >= stime).all()
        rts = []
        for item in a:
            temp = dict(name=item.name, stime=str(item.meetingstime), etime=str(item.meetingetime),
                        meetingroom=item.meetingroom,
                        creatername=item.creater.nickname, createrdep=item.creater.department, id=item.id)
            rts.append(temp)
            # rts = json.dumps(a, cls=AlchemyEncoder,ensure_ascii=False)
        return json.dumps(rts, ensure_ascii=False)  # rts


# 会议展示系统
@meeting_page.route("/meetingshow", methods=["GET", "POST"])
def meetingshow():
    year = datetime.datetime.now().year
    month = datetime.datetime.now().month
    day = datetime.datetime.now().day
    week = datetime.datetime.now().isoweekday()
    stime = date.today()
    etime = (date.today() + timedelta(days=1)).strftime("%Y-%m-%d")
    a = Order.query.filter(Order.mark == 2, Order.city == "太原", Order.meetingstime <= etime,
                           Order.meetingstime >= stime).join(Room, Room.name == Order.meetingroom).order_by(
        Room.orderid, Order.meetingstime).all()

    return ops_render("/meetingshow/meetingshow.html", {"a": a, "year": year, "month": month, "day": day, "week": week})

# 会议展示系统
@meeting_page.route("/meetingshowhigh", methods=["GET", "POST"])
def meetingshowhigh():
    year = datetime.datetime.now().year
    month = datetime.datetime.now().month
    day = datetime.datetime.now().day
    week = datetime.datetime.now().isoweekday()
    stime = date.today()
    etime = (date.today() + timedelta(days=1)).strftime("%Y-%m-%d")
    a = Order.query.filter(Order.mark == 2, Order.city == "太原", Order.meetingstime <= etime,
                           Order.meetingstime >= stime).join(Room, Room.name == Order.meetingroom).order_by(
        Room.orderid, Order.meetingstime).all()

    return ops_render("/meetingshow/meetingshowhigh.html", {"a": a, "year": year, "month": month, "day": day, "week": week})


# 会议展示系统(明日）
@meeting_page.route("/meetingshow2", methods=["GET", "POST"])
def meetingshow2():
    tomorrow = (date.today() + timedelta(days=1)).strftime("%Y-%m-%d")
    year = int(tomorrow[0:4])
    month = int(tomorrow[5:7])
    day = int(tomorrow[8:10])
    week = datetime.datetime(year, month, day).isoweekday()

    a = Order.query.filter(Order.mark == 2, Order.city == "太原", Order.meetingdate == tomorrow
                          ).join(Room, Room.name == Order.meetingroom).order_by(
        Room.orderid, Order.meetingstime).all()

    return ops_render("/meetingshow/meetingshow.html", {"a": a, "year": year, "month": month, "day": day, "week": week})


# 会议管理员首页
@meeting_page.route('/meetingadmin', methods=['GET', 'POST'])
def meetingadmin():
    city = request.args.get('city')
    stime = date.today()
    etime = (date.today() + timedelta(days=1)).strftime("%Y-%m-%d")
    meeting = Order.query.filter(Order.mark != 0, Order.city == city, Order.meetingstime <= etime,
                                 Order.meetingstime >= stime).join(Room, Room.name == Order.meetingroom).order_by(
        Order.mark.desc(),
        Room.orderid, Order.meetingstime).all()

    return ops_render("/admin/meetingadmin.html", {"meeting": meeting})


# 管理员查找(范围）
@meeting_page.route('/meetingsearch', methods=['GET', 'POST'])
def meetingsearch():
    stime = request.args.get('stime')
    etime = request.args.get('etime')
    city = request.args.get('city')

    meeting = Order.query.filter(Order.mark != 0, Order.city == city, Order.meetingstime <= etime,
                                 Order.meetingstime >= stime).join(Room, Room.name == Order.meetingroom).order_by(
        Order.mark.desc(),
        Room.orderid, Order.meetingstime).all()

    return ops_render("/admin/meetingadmin.html", {"meeting": meeting})


# 管理员查找(单点）
@meeting_page.route('/meetingsearch2', methods=['GET', 'POST'])
def meetingsearch2():
    date = request.args.get('date')
    city = request.args.get('city')
    meeting = Order.query.filter(Order.mark != 0, Order.city == city, Order.meetingdate == date).join(Room,
                                                                                                      Room.name == Order.meetingroom).order_by(
        Order.mark.desc(),
        Room.orderid, Order.meetingstime).all()

    return ops_render("/admin/meetingadmin.html", {"meeting": meeting})


# 管理员更新会议信息
@meeting_page.route("/adminupdate", methods=["GET", "POST"])
def adminupdate():
    id = request.form.get('id')
    name = request.form.get('name')
    meetingroom = request.form.get('meetingroom')
    date = request.form.get('date')
    stime = request.form.get('stime')
    etime = request.form.get('etime')
    uid = request.form.get('uid')
    stime = date + " " + stime
    etime = date + " " + etime

    order = Order.query.filter_by(id=id).first()
    city = order.city
    order.name = name
    order.meetingdate = date
    order.uid = uid
    order.meetingstime = stime
    order.meetingetime = etime
    order.meetingroom = meetingroom
    order.updated_time = getCurrentTime()
    db.session.commit()

    # 返回首页数据

    return redirect('meetingsearch2?city=' + city + '&date=' + date)



# 会议展示系统
@meeting_page.route("/bigshow", methods=["GET", "POST"])
def bigshow():
    year = datetime.datetime.now().year
    month = datetime.datetime.now().month
    day = datetime.datetime.now().day
    week = datetime.datetime.now().isoweekday()

    url = "https://devapi.qweather.com/v7/weather/now?location=101100101&key=b632b25bd3c949e79704c47dad5e8607"
    rep = requests.get(url)
    rep.encoding = 'utf-8'
    repJson = rep.json()
    weather = repJson.get('now')
    text = weather["text"]
    icon = weather["icon"]
    temp = weather["temp"]
    feelsLike = weather["feelsLike"]
    windDir = weather["windDir"]
    humidity = weather["humidity"]

    weatherinfo1 = text + " " + windDir
    weatherinfo2 = "气温:" + temp + "℃  体感温度:"+feelsLike+ "℃"
    weatherinfo3 = "相对湿度:" + humidity + "%"
    gg = Document.query.filter_by(type="大屏展示",classone="公告").order_by(
        Document.id.desc()).first()
    ggurl = gg.image

    srb = Document.query.filter_by(type="大屏展示", classone="生日榜").order_by(
        Document.id.desc()).first()
    srburl = srb.image

    hd = Document.query.filter_by(type="大屏展示", classone="活动").order_by(
        Document.id.desc()).first()
    hdurl = hd.image

    return ops_render("/meetingshow/bigshow.html", {"year": year, "month": month, "day": day, "week": week,"weatherinfo1":weatherinfo1,"weatherinfo2":weatherinfo2,"weatherinfo3":weatherinfo3,"ggurl": ggurl, "srburl": srburl, "hdurl": hdurl,"icon":icon})



@meeting_page.route('/upload', methods=['GET', 'POST'])
def uploadfile():
    # 从前端获取文件
    f = request.files.get('files')
    classone = request.form.get('classone')
    type = request.form.get('type')
    file = f.read()

    access_key = 'po98t2WFtFrNvPJ_bZTFobndhhKhQUk6mrXq2NX1'
    secret_key = 'DbooW85jje3wtiDP0se_JLL76PjgLGc-3p2fiEaZ'
    # 构建鉴权对象
    q = Auth(access_key, secret_key)
    # 要上传的空间
    bucket_name = 'guanzhuoran'
    # http://+外链域名
    domian_name = 'http://upload.guanzhuoran.cn/'
    # 生成上传 Token，可以指定过期时间等

    now = time.time()

    uploadname = str(int(now))

    token = q.upload_token(bucket_name, uploadname, 3600)

    ret, info = put_data(token, uploadname, data=file)

    url = domian_name + uploadname

    order = Document()
    order.type = type
    order.classone = classone
    order.title = uploadname
    order.image = url
    db.session.add(order)
    db.session.commit()

    return ops_renderJSON(msg="上传成功")


# 图片展示
@meeting_page.route("/imgshow", methods=["GET", "POST"])
def imgshow():

    return ops_render("/meetingshow/showimg.html")

@meeting_page.route("/imgshow43", methods=["GET", "POST"])
def imgshow43():

    return ops_render("/meetingshow/showimg43.html")